package com.wzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.domain.ResponseResult;
import com.wzy.domain.bo.SysCommentMsgBO;
import com.wzy.domain.entity.Comment;
import com.wzy.domain.entity.Event;
import com.wzy.domain.entity.SysMessage;
import com.wzy.domain.vo.PageVO;
import com.wzy.event.EventProducer;
import com.wzy.mapper.ArticleMapper;
import com.wzy.mapper.SysMessageMapper;
import com.wzy.service.SysMessageService;
import com.wzy.service.UserCommonService;
import com.wzy.util.RedisCache;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wzy.constant.RedisConstants.*;
import static com.wzy.constant.SystemConstants.*;

/**
 * 系统消息 业务层
 */
@Service
@RequiredArgsConstructor
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage>
        implements SysMessageService
{
    private final EventProducer eventProducer;
    private final ArticleMapper articleMapper;
    private final RedisCache redisCache;
    private final HttpServletRequest httpServletRequest;
    private final UserCommonService userCommonService;

    /**
     * 生产评论消息
     */
    @Override
    @Async
    public void sendCommentMessage(Comment comment)
    {
        boolean isRootComment = comment.getRootId().equals(ROOT_COMMENT);
        Long entityUserId;
        if (isRootComment)
        {
            entityUserId = articleMapper.selectById(comment.getArticleId()).getCreateBy();
        }
        else
        {
            entityUserId = comment.getToCommentUserId();
        }

        // 生产评论消息
        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setEntityId(comment.getId())
                .setUserId(comment.getCreateBy())
                .setUserNick(comment.getCreateNick())
                .setEntityUserId(entityUserId)
                .setAvatarUrl(comment.getAvatarUrl())
                .setData("goToArticle", comment.getArticleId())
                .setData("isRootComment", isRootComment)
                .setData("filterContent", comment.getFilterContent());
        eventProducer.fireEvent(event);
    }

    /**
     * 获取未读消息数
     */
    @Override
    public ResponseResult<Map<String, Integer>> getSystemMessageNum()
    {
        Long userId = userCommonService.getRedisUserId(httpServletRequest);
        Integer commentNum = redisCache.getCacheObject(SYSTEM_MESSAGE_COMMENT_NUM_KEY + userId);
        Map<String, Integer> data = new HashMap<>();
        data.put("systemMsg", commentNum);
        data.put("commentNum", commentNum);
        return ResponseResult.okResult(data);
    }

    /**
     * 修改消息状态
     */
    @Override
    public ResponseResult<Map<String, Integer>> updateSysMessageStatus(String type)
    {
        Long userId = userCommonService.getRedisUserId(httpServletRequest);
        String msgKey;
        switch (type)
        {
            case TOPIC_COMMENT:
                msgKey = SYSTEM_MESSAGE_COMMENT_NUM_KEY;
                break;
            case TOPIC_LIKE:
                msgKey = SYSTEM_MESSAGE_LIKE_NUM_KEY;
                break;
            case TOPIC_FOLLOW:
                msgKey = SYSTEM_MESSAGE_FOLLOW_NUM_KEY;
                break;
            default:
                log.error("未知主题: {}" + type);
                throw new IllegalStateException("未知主题: " + type);
        }
        redisCache.deleteObject(msgKey + userId);
        return ResponseResult.okResult();
    }

    /**
     * 查询“回复我的”系统消息
     */
    @Override
    public ResponseResult<PageVO> getSysCommentMsgList(SysCommentMsgBO sysCommentMsgBO)
    {
        Long userId = userCommonService.getRedisUserId(httpServletRequest);
        Page<SysMessage> page = sysCommentMsgBO.build();
        page(page, new LambdaQueryWrapper<SysMessage>()
                .eq(SysMessage::getToId, userId)
                .eq(SysMessage::getConversationType, sysCommentMsgBO.getConversationType())
                .like(StringUtils.isNotBlank(sysCommentMsgBO.getContent()),
                        SysMessage::getContent, sysCommentMsgBO.getContent())
                .orderByDesc(SysMessage::getCreateTime));
        List<SysMessage> messages = page.getRecords();

        PageVO pageVO = new PageVO(messages, page.getTotal());

        return ResponseResult.okResult(pageVO);
    }

}




